<?php

namespace app\admin\model;

use app\admin\model\book\Files;
use think\Model;
use traits\model\SoftDelete;

class Book extends Model
{

    use SoftDelete;

    

    // 表名
    protected $name = 'book';
    
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'integer';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    protected $deleteTime = 'deletetime';

    // 追加属性
    protected $append = ['status_text','class_text','publisher_text','year_text','grade_text', 'unit_list'];
    

    protected static function init()
    {
        self::afterInsert(function ($row) {
            if (!isset($row['weigh']) || !$row['weigh']) {
                $pk = $row->getPk();
                $row->getQuery()->where($pk, $row[$pk])->update(['weigh' => $row[$pk]]);
            }
        });
    }

	public function getClassList(){
		return config('site.book_class');
	}

	public function getClassTextAttr($value, $data){
		$value = $value ?: ($data['class_id'] ?? '');
		$list = $this->getClassList();
		return $list[$value] ?? '';
	}

	public function getPublisherList(){
		return config('site.book_publisher');
	}

	public function getPublisherTextAttr($value, $data){
		$value = $value ?: ($data['publisher_id'] ?? '');
		$list = $this->getPublisherList();
		return $list[$value] ?? '';
	}

	public function getYearList(){
		return config('site.book_year');
	}

	public function getYearTextAttr($value, $data){
		$value = $value ?: ($data['year'] ?? '');
		$list = $this->getYearList();
		return $list[$value] ?? '';
	}

	public function getGradeList(){
		return config('site.book_grade');
	}

	public function getGradeTextAttr($value, $data){
		$value = $value ?: ($data['grade_id'] ?? '');
		$list = $this->getGradeList();
		return $list[$value] ?? '';
	}


    public function getStatusList()
    {
        return ['normal' => __('Normal'), 'hidden' => __('Hidden')];
    }


    public function getStatusTextAttr($value, $data)
    {
        $value = $value ?: ($data['status'] ?? '');
        $list = $this->getStatusList();
        return $list[$value] ?? '';
    }


	public function getUnitListAttr($value, $data){
		$value = $value ?: ($data['unit'] ?? '');
		return json_decode($value, true);
	}

	/**
     * 附件
     * @return \think\model\relation\HasMany
     */
    public function files(){
        return $this->hasMany(Files::class,'book_id');
    }

}
